package cn.kgc.springday05.dynamic;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @author 课工场
 * @date 2023/10/10
 * @description  Cglib 代理   基于父子类关系的代理
 */
public class CglibProxy {

    private Object target;

    public CglibProxy(Object target){
        this.target = target;
    }

    public Object getTargetProxy(){

        Enhancer enhancer = new Enhancer();

        // 设置代理对象的父类
        enhancer.setSuperclass(target.getClass());
        // 设置增强的业务
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                System.out.println("-----------开始打印日志-------------");

                Object invoke = method.invoke(target, objects);

                System.out.println("-----------结束打印日志-------------");

                return invoke;
            }
        };
        enhancer.setCallback(invocationHandler);

        Object o = enhancer.create();

        return o;
    }
}
